package com.longway.core.ext.kit.excel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.longway.core.toolbox.Func;

public class PoiExporter {

    public static final String VERSION_2003 = "2003";
    private static final int HEADER_ROW = 1;
    private static final int MAX_ROWS = 65535;
    private String version;
    private String[] sheetNames = new String[]{"sheet"};
    private int cellWidth = 20;
    private int headerRow;
    private String[][] headers;
    private String[][] columns;
    private List<?>[] data;
    private Map<Integer, Integer> colwidths;
    private short contentHeight = 400;

    public PoiExporter(List<?>... data) {
        this.data = data;
    }

    public static PoiExporter data(List<?>... data) {
        return new PoiExporter(data);
    }

    public static List<List<?>> dice(List<?> num, int chunkSize) {
        int size = num.size();
        int chunk_num = size / chunkSize + (size % chunkSize == 0 ? 0 : 1);
        List<List<?>> result = new ArrayList<List<?>>();
        for (int i = 0; i < chunk_num; i++) {
        	List<?> res = new ArrayList<>(num.subList(i * chunkSize, i == chunk_num - 1 ? size : (i + 1) * chunkSize));
            result.add(res);
        }
        return result;
    }

    public Workbook export() {
    	if(Func.isEmpty(data)){
    		 throw new NullPointerException("data can not be null");
    	}
    	if(Func.isEmpty(headers)){
   		 	throw new NullPointerException("headers can not be null");
    	}
    	if(Func.isEmpty(columns)){
   		 	throw new NullPointerException("columns can not be null");
    	}
    	if(!(data.length == sheetNames.length && sheetNames.length == headers.length && headers.length == columns.length)){
    		throw new IllegalArgumentException(String.valueOf("data,sheetNames,headers and columns'length should be the same." +
    	                "(data:" + data.length + ",sheetNames:" + sheetNames.length + ",headers:" + headers.length + ",columns:" + columns.length + ")"));
    	}
    	if(!(cellWidth >= 0)){
    		throw new IllegalArgumentException("cellWidth can not be less than 0");
    	}
        Workbook wb;
        if (VERSION_2003.equals(version)) {
            wb = new HSSFWorkbook();
            if (data.length > 1) {
                for (int i = 0; i < data.length; i++) {
                    List<?> item = data[i];
                    if(!(item.size() < MAX_ROWS)){
                    	throw new IllegalArgumentException("Data [" + i + "] is invalid:invalid data size (" + item.size() + ") outside allowable range (0..65535)");
                    }
                }
            } else if (data.length == 1 && data[0].size() > MAX_ROWS) {
                data = dice(data[0], MAX_ROWS).toArray(new List<?>[]{});
                String sheetName = sheetNames[0];
                sheetNames = new String[data.length];
                for (int i = 0; i < data.length; i++) {
                    sheetNames[i] = sheetName + (i == 0 ? "" : (i + 1));
                }
                String[] header = headers[0];
                headers = new String[data.length][];
                for (int i = 0; i < data.length; i++) {
                    headers[i] = header;
                }
                String[] column = columns[0];
                columns = new String[data.length][];
                for (int i = 0; i < data.length; i++) {
                    columns[i] = column;
                }
            }
        } else {
            wb = new XSSFWorkbook();
        }
        //表头样式
        CellStyle headerStyle = getDefaultHeaderStyle(wb);
        if (data.length == 0) {
            return wb;
        }
        for (int i = 0; i < data.length; i++) {
            Sheet sheet = wb.createSheet(sheetNames[i]);
            Row row;
            Cell cell;
            if (headers[i].length > 0) {
                row = sheet.createRow(0);
                row.setHeight((short)500);
                if (headerRow <= 0) {
                    headerRow = HEADER_ROW;
                }
                headerRow = Math.min(headerRow, MAX_ROWS);
                for (int h = 0, lenH = headers[i].length; h < lenH; h++) {
                    if(colwidths!=null&&colwidths.get(h)!=null){
                    	sheet.setColumnWidth(h, 256*colwidths.get(h)+184);
                    }else{
                    	sheet.setColumnWidth(h, 256*cellWidth+184);
                    }
                    cell = row.createCell(h);
                    cell.setCellValue(headers[i][h]);
                    cell.setCellStyle(headerStyle);
                }
            }

            for (int j = 0, len = data[i].size(); j < len; j++) {
                row = sheet.createRow(j + headerRow);
                row.setHeight(contentHeight);
                Object obj = data[i].get(j);
                if (obj == null) {
                    continue;
                }
                if (obj instanceof Map) {
                    processAsMap(columns[i], row, obj);
                } else if (obj instanceof Model) {
                    processAsModel(columns[i], row, obj);
                } else if (obj instanceof Record) {
                    processAsRecord(columns[i], row, obj);
                } else {
                    throw new RuntimeException("Not support type[" + obj.getClass() + "]");
                }
            }
        }
        return wb;
    }
    
    private static CellStyle getDefaultHeaderStyle(Workbook wb){
    	CellStyle style = wb.createCellStyle();
        Font font = wb.createFont(); 
        font.setFontName("仿宋_GB2312");
    /*    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示  
        font.setFontHeightInPoints((short) 12);  
 		style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框  
 		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框  
 		style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框  
 		style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框  
 		style.setWrapText(true);//设置自动换行  
 		style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
 		style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);//垂直居中
*/ 		style.setFont(font);
 		style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); // 前景色
 		//style.setFillPattern(CellStyle.SOLID_FOREGROUND);  
 		return style;
    }

    @SuppressWarnings("unchecked")
    private static void processAsMap(String[] columns, Row row, Object obj) {
        Cell cell;
        Map<String, Object> map = (Map<String, Object>) obj;
        if (columns.length == 0) { // show all if column not specified
            Set<String> keys = map.keySet();
            int columnIndex = 0;
            for (String key : keys) {
                cell = row.createCell(columnIndex);
                cell.setCellValue(map.get(key) + "");
                columnIndex++;
            }
        } else {
            for (int j = 0, len = columns.length; j < len; j++) {
                cell = row.createCell(j);
                cell.setCellValue(map.get(columns[j]) == null ? "" : map.get(columns[j]) + "");
            }
        }
    }

    private static void processAsModel(String[] columns, Row row, Object obj) {
        Cell cell;
        Model<?> model = (Model<?>) obj;
        Set<Entry<String, Object>> entries = model._getAttrsEntrySet();
        if (columns.length == 0) { // show all if column not specified
            int columnIndex = 0;
            for (Entry<String, Object> entry : entries) {
                cell = row.createCell(columnIndex);
                cell.setCellValue(entry.getValue() + "");
                columnIndex++;
            }
        } else {
            for (int j = 0, len = columns.length; j < len; j++) {
                cell = row.createCell(j);
                cell.setCellValue(model.get(columns[j]) == null ? "" : model.get(columns[j]) + "");
            }
        }
    }

    private static void processAsRecord(String[] columns, Row row, Object obj) {
        Cell cell;
        Record record = (Record) obj;
        Map<String, Object> map = record.getColumns();
        if (columns.length == 0) { // show all if column not specified
            record.getColumns();
            Set<String> keys = map.keySet();
            int columnIndex = 0;
            for (String key : keys) {
                cell = row.createCell(columnIndex);
                cell.setCellValue(record.get(key) + "");
                columnIndex++;
            }
        } else {
            for (int j = 0, len = columns.length; j < len; j++) {
                cell = row.createCell(j);
                cell.setCellValue(map.get(columns[j]) == null ? "" : map.get(columns[j]) + "");
            }
        }
    }

    public PoiExporter version(String version) {
        this.version = version;
        return this;
    }

    public PoiExporter sheetName(String sheetName) {
        this.sheetNames = new String[]{sheetName};
        return this;
    }

    public PoiExporter sheetNames(String... sheetName) {
        this.sheetNames = sheetName;
        return this;
    }

    public PoiExporter cellWidth(int cellWidth) {
        this.cellWidth = cellWidth;
        return this;
    }

    public PoiExporter headerRow(int headerRow) {
        this.headerRow = headerRow;
        return this;
    }

    public PoiExporter header(String... header) {
        this.headers = new String[][]{header};
        return this;
    }

    public PoiExporter headers(String[]... headers) {
        this.headers = headers;
        return this;
    }

    public PoiExporter column(String... column) {
        this.columns = new String[][]{column};
        return this;
    }

    public PoiExporter columns(String[]... columns) {
        this.columns = columns;
        return this;
    }
    
    public PoiExporter colwidths(Map<Integer, Integer> colwidths) {
        this.colwidths = colwidths;
        return this;
    }
    
    public PoiExporter version(short contentHeight) {
        this.contentHeight = contentHeight;
        return this;
    }

}
